Popular Searches
Popular Course Categories
Popular Courses

Practicing Java Operators, Conditions, and Loop-Based Problems

Practicing Java Operators, Conditions, and Loop-Based Problems

Core Java Projects, Interview Preparation, and Career Readiness

Practicing Java Operators, Conditions, and Loop-Based Problems

Course: Core Java Training

Topic: Practicing Java Operators, Conditions, and Loop-Based Problems

Course Link: Core Java Training – JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction

Java operators, conditional statements, and loops are fundamental building blocks of programming. Operators perform calculations and comparisons, conditions help a program make decisions, and loops repeat instructions until a particular condition is met.

Practicing these concepts through small programming problems helps learners develop logical thinking, understand program flow, and prepare for coding interviews. Many common beginner problems, such as checking even or odd numbers, finding the largest value, calculating factorials, checking prime numbers, and generating multiplication tables, use these concepts together.

2. Learning Objectives

  • Understand arithmetic, relational, logical, assignment, and unary operators.
  • Apply operator precedence and parentheses correctly.
  • Use if, if-else, nested if, and switch statements.
  • Write programs using for, while, and do-while loops.
  • Use break and continue to control loop execution.
  • Solve number-based and pattern-printing problems.
  • Identify common logical errors and improve program readability.
  • Practice coding problems frequently asked in beginner-level Java interviews.

3. Understanding Java Operators

An operator is a symbol that performs an operation on one or more operands. Operands are the values or variables on which an operation is performed.

For example, in int sum = 10 + 20;, the plus sign is an operator, while 10 and 20 are operands.

3.1 Arithmetic Operators

Arithmetic operators perform mathematical calculations.

Operator Purpose Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
% Remainder 10 % 3 1

Important: When both operands are integers, Java performs integer division. For example, 7 / 2 produces 3, not 3.5. Use a floating-point operand, such as 7.0 / 2, when a decimal result is required.

3.2 Relational Operators

Relational operators compare two values and return a boolean result: true or false.

Operator Meaning Example
== Equal to 5 == 5 returns true
!= Not equal to 5 != 3 returns true
> Greater than 8 > 4 returns true
< Less than 3 < 7 returns true
>= Greater than or equal to 5 >= 5 returns true
<= Less than or equal to 4 <= 6 returns true

3.3 Logical Operators

Logical operators combine or reverse boolean expressions.

Operator Meaning Example
&& Logical AND; both conditions must be true. age >= 18 && age <= 60
|| Logical OR; at least one condition must be true. day == 6 || day == 7
! Logical NOT; reverses a boolean value. !isValid

Java's && and || operators use short-circuit evaluation. The second expression may not be evaluated when the first expression already determines the result.

3.4 Assignment Operators

Assignment operators assign or update variable values.

int number = 10;
number += 5;  // number = number + 5
number -= 2;  // number = number - 2
number *= 3;  // number = number * 3
number /= 2;  // number = number / 2
number %= 4;  // number = number % 4

3.5 Increment and Decrement Operators

The increment operator ++ increases a variable by one. The decrement operator -- decreases it by one.

int a = 5;
a++;
System.out.println(a); // 6

int b = 5;
b--;
System.out.println(b); // 4

In prefix form, such as ++a, the variable is updated before its value is used in the surrounding expression. In postfix form, such as a++, the original value is used first and the variable is then updated.

3.6 Ternary Operator

The ternary operator is a compact alternative to a simple if-else expression.

int age = 20;
String result = age >= 18 ? "Adult" : "Minor";
System.out.println(result);

Output:

Adult

3.7 Operator Precedence

Operator precedence determines which operations are evaluated first. Parentheses can make the intended order explicit.

int result1 = 10 + 5 * 2;
int result2 = (10 + 5) * 2;

System.out.println(result1); // 20
System.out.println(result2); // 30

Multiplication has higher precedence than addition, so parentheses change the second result.

4. Conditional Statements in Java

Conditional statements allow a program to execute different instructions depending on whether specified conditions are true or false.

4.1 The if Statement

The if statement executes a block only when its condition evaluates to true.

int number = 10;

if (number > 0) {
    System.out.println("Positive number");
}

Output:

Positive number

4.2 The if-else Statement

The if-else statement selects between two alternative blocks.

int number = 7;

if (number % 2 == 0) {
    System.out.println("Even number");
} else {
    System.out.println("Odd number");
}

Output:

Odd number

4.3 The else-if Ladder

An else-if ladder checks multiple conditions in order. The first condition that evaluates to true determines the block that executes.

int marks = 82;

if (marks >= 90) {
    System.out.println("Grade A");
} else if (marks >= 75) {
    System.out.println("Grade B");
} else if (marks >= 60) {
    System.out.println("Grade C");
} else if (marks >= 40) {
    System.out.println("Grade D");
} else {
    System.out.println("Fail");
}

Output:

Grade B

The order of the conditions matters. Check higher grade boundaries first to avoid assigning a lower grade incorrectly.

4.4 Nested if Statements

A nested if statement is an if statement placed inside another if statement. It is useful when a second decision depends on the first.

int age = 25;
boolean hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        System.out.println("Eligible to drive");
    } else {
        System.out.println("License required");
    }
} else {
    System.out.println("Too young to drive");
}

Output:

Eligible to drive

4.5 The switch Statement

The switch statement selects a branch based on a value. It is useful when a variable is compared against several fixed alternatives.

int day = 3;

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Invalid day");
}

Output:

Wednesday

In the traditional switch statement, break prevents execution from continuing into the next case. Without it, execution can fall through to subsequent cases. Switch expressions and arrow labels were introduced in newer Java versions; the example above uses traditional syntax suitable for Java 8.

5. Looping Statements in Java

Loops repeat a block of code while a condition remains true or for a specified number of iterations. They are essential for processing collections, generating sequences, calculating totals, and solving number problems.

5.1 The for Loop

A for loop is commonly used when the number of iterations is known.

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

Output:

1
2
3
4
5

The loop contains three main parts: initialization, condition, and update.

  • Initialization: Runs once before the loop begins.
  • Condition: Checked before each iteration.
  • Update: Runs after each iteration.

5.2 The while Loop

A while loop checks its condition before executing the body. It is useful when the number of repetitions depends on a condition.

int i = 1;

while (i <= 5) {
    System.out.println(i);
    i++;
}

Output:

1
2
3
4
5

5.3 The do-while Loop

A do-while loop executes its body at least once because the condition is checked after the body.

int i = 1;

do {
    System.out.println(i);
    i++;
} while (i <= 5);

Output:

1
2
3
4
5

5.4 Difference Between for, while, and do-while

Loop Condition Check Minimum Executions Typical Use
for Before each iteration Zero Counting through a known range.
while Before each iteration Zero Repeating until a condition changes.
do-while After each iteration One Running a menu or operation at least once.

5.5 The break Statement

The break statement immediately terminates the nearest enclosing loop or traditional switch statement.

for (int i = 1; i <= 10; i++) {
    if (i == 6) {
        break;
    }
    System.out.println(i);
}

Output:

1
2
3
4
5

5.6 The continue Statement

The continue statement skips the remaining statements in the current loop iteration and proceeds to the next iteration.

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;
    }
    System.out.println(i);
}

Output:

1
2
4
5

6. Problem-Solving Approach

Before writing code for a problem, understand the required input, expected output, constraints, and logical steps. A structured approach reduces mistakes and makes the program easier to test.

  1. Understand the problem: Identify exactly what needs to be calculated or checked.
  2. Identify inputs: Determine the required values and their data types.
  3. Plan the logic: Decide whether operators, conditions, loops, or a combination is needed.
  4. Write pseudocode: Describe the solution in simple steps before implementing Java syntax.
  5. Implement the program: Translate the logic into readable Java code.
  6. Test edge cases: Check zero, negative values, boundary values, and invalid inputs where applicable.
  7. Review the result: Verify the output and ensure that the loop terminates correctly.

7. Practice Problem 1: Check Whether a Number Is Even or Odd

Problem: Write a program to determine whether an integer is even or odd.

Logic: If the remainder after division by 2 is zero, the number is even. Otherwise, it is odd.

import java.util.Scanner;

public class EvenOdd {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter an integer: ");
        int number = scanner.nextInt();

        if (number % 2 == 0) {
            System.out.println("Even number");
        } else {
            System.out.println("Odd number");
        }

        scanner.close();
    }
}

Sample input:

12

Sample output:

Even number

Concepts used: Modulus operator, if-else statement, and user input.

8. Practice Problem 2: Find the Largest of Three Numbers

Problem: Find the largest value among three integers.

public class LargestOfThree {
    public static void main(String[] args) {
        int a = 25;
        int b = 40;
        int c = 15;

        if (a >= b && a >= c) {
            System.out.println("Largest: " + a);
        } else if (b >= a && b >= c) {
            System.out.println("Largest: " + b);
        } else {
            System.out.println("Largest: " + c);
        }
    }
}

Output:

Largest: 40

Explanation: Each condition compares one number with the other two. The greater-than-or-equal operator also handles cases where two or more values are equal.

9. Practice Problem 3: Check Positive, Negative, or Zero

Problem: Determine whether a number is positive, negative, or zero.

public class NumberSign {
    public static void main(String[] args) {
        int number = -8;

        if (number > 0) {
            System.out.println("Positive");
        } else if (number < 0) {
            System.out.println("Negative");
        } else {
            System.out.println("Zero");
        }
    }
}

Output:

Negative

Concepts used: Relational operators and an else-if ladder.

10. Practice Problem 4: Check Leap Year

Problem: Determine whether a year is a leap year in the Gregorian calendar.

Rules: A year is a leap year if it is divisible by 400, or if it is divisible by 4 but not by 100.

public class LeapYear {
    public static void main(String[] args) {
        int year = 2024;

        if (year % 400 == 0 ||
            (year % 4 == 0 && year % 100 != 0)) {
            System.out.println("Leap year");
        } else {
            System.out.println("Not a leap year");
        }
    }
}

Output:

Leap year

Test cases:

Year Expected Result Reason
2024 Leap year Divisible by 4 but not by 100.
1900 Not a leap year Divisible by 100 but not by 400.
2000 Leap year Divisible by 400.
2023 Not a leap year Not divisible by 4.

11. Practice Problem 5: Print a Multiplication Table

Problem: Print the multiplication table of a given number from 1 to 10.

public class MultiplicationTable {
    public static void main(String[] args) {
        int number = 5;

        for (int i = 1; i <= 10; i++) {
            System.out.println(
                number + " x " + i + " = " + (number * i)
            );
        }
    }
}

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Concepts used: for loop, multiplication, and string concatenation.

12. Practice Problem 6: Calculate the Factorial of a Number

Problem: Calculate the factorial of a non-negative integer. The factorial of n, written as n!, is the product of all positive integers from 1 through n. By definition, 0! equals 1.

public class FactorialDemo {
    public static void main(String[] args) {
        int number = 5;
        long factorial = 1;

        if (number < 0) {
            System.out.println(
                "Factorial is not defined for negative integers"
            );
        } else {
            for (int i = 1; i <= number; i++) {
                factorial *= i;
            }

            System.out.println("Factorial: " + factorial);
        }
    }
}

Output:

Factorial: 120

Explanation: The loop multiplies the running result by each integer from 1 to the specified number. Starting the result at 1 also correctly handles 0!.

Note: Even the long data type has a limited range. Large factorials will overflow and require a different approach, such as BigInteger.

13. Practice Problem 7: Find the Sum of Natural Numbers

Problem: Calculate the sum of natural numbers from 1 through n.

public class NaturalNumberSum {
    public static void main(String[] args) {
        int n = 10;
        int sum = 0;

        for (int i = 1; i <= n; i++) {
            sum += i;
        }

        System.out.println("Sum: " + sum);
    }
}

Output:

Sum: 55

The loop-based solution is useful for practicing accumulation. An alternative mathematical formula is n * (n + 1) / 2, provided the calculation uses a suitable numeric type and does not overflow.

14. Practice Problem 8: Reverse a Number

Problem: Reverse the digits of a positive integer.

public class ReverseNumber {
    public static void main(String[] args) {
        int number = 12345;
        int reversed = 0;

        while (number > 0) {
            int digit = number % 10;
            reversed = reversed * 10 + digit;
            number /= 10;
        }

        System.out.println("Reversed: " + reversed);
    }
}

Output:

Reversed: 54321

Explanation:

  • number % 10 extracts the last digit.
  • reversed * 10 + digit appends that digit to the reversed number.
  • number / 10 removes the last digit through integer division.

This basic example assumes a non-negative input and does not handle integer overflow. Consider how negative values and trailing zeros should be handled when extending the solution.

15. Practice Problem 9: Check Whether a Number Is a Palindrome

Problem: A number is a palindrome if it reads the same forward and backward. For example, 121 is a palindrome.

public class NumberPalindrome {
    public static void main(String[] args) {
        int number = 121;
        int original = number;
        int reversed = 0;

        while (number > 0) {
            int digit = number % 10;
            reversed = reversed * 10 + digit;
            number /= 10;
        }

        if (original == reversed) {
            System.out.println("Palindrome number");
        } else {
            System.out.println("Not a palindrome");
        }
    }
}

Output:

Palindrome number

This version is designed for non-negative integer inputs. The original number is saved because the loop changes the working variable.

16. Practice Problem 10: Check Whether a Number Is Prime

Problem: A prime number is an integer greater than 1 that has exactly two positive divisors: 1 and itself.

public class PrimeNumber {
    public static void main(String[] args) {
        int number = 29;
        boolean isPrime = number > 1;

        for (int i = 2; i <= number / i; i++) {
            if (number % i == 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime) {
            System.out.println("Prime number");
        } else {
            System.out.println("Not a prime number");
        }
    }
}

Output:

Prime number

Explanation: A composite number must have a divisor no larger than its square root. The condition i <= number / i avoids multiplying i * i, which could overflow for large integers.

17. Practice Problem 11: Count the Digits in a Number

Problem: Count how many digits an integer contains.

public class CountDigits {
    public static void main(String[] args) {
        int number = 50721;
        int count = 0;

        do {
            count++;
            number /= 10;
        } while (number != 0);

        System.out.println("Digit count: " + count);
    }
}

Output:

Digit count: 5

The do-while loop also counts zero as one digit. For a complete solution, decide how negative inputs should be handled; the minus sign is not itself a digit.

18. Practice Problem 12: Calculate the Sum of Digits

Problem: Add all the digits of a non-negative integer.

public class SumOfDigits {
    public static void main(String[] args) {
        int number = 1234;
        int sum = 0;

        while (number > 0) {
            sum += number % 10;
            number /= 10;
        }

        System.out.println("Sum of digits: " + sum);
    }
}

Output:

Sum of digits: 10

Explanation: The modulus operator extracts each digit, and integer division removes that digit from the working number. For zero or negative inputs, adapt the loop to the intended requirements.

19. Practice Problem 13: Print the Fibonacci Series

Problem: Print the first n terms of the Fibonacci sequence. Each term after the first two is the sum of the two preceding terms.

public class FibonacciSeries {
    public static void main(String[] args) {
        int terms = 10;
        long first = 0;
        long second = 1;

        for (int i = 1; i <= terms; i++) {
            System.out.print(first + " ");

            long next = first + second;
            first = second;
            second = next;
        }
    }
}

Output:

0 1 1 2 3 5 8 13 21 34

Concepts used: for loop, variable updates, and arithmetic operations. For sufficiently large sequences, values exceed the range of long.

20. Practice Problem 14: Print a Star Pattern

Problem: Print a right-angled triangle using nested loops.

public class StarPattern {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output:

*
* *
* * *
* * * *
* * * * *

The outer loop controls the rows, while the inner loop controls how many stars are printed in each row.

21. Practice Problem 15: Check an Armstrong Number

Problem: An Armstrong number is a non-negative integer equal to the sum of each digit raised to the power of the number of digits. For example, 153 equals 1³ + 5³ + 3³.

public class ArmstrongNumber {
    public static void main(String[] args) {
        int number = 153;
        int original = number;
        int digits = String.valueOf(number).length();
        int sum = 0;

        while (number > 0) {
            int digit = number % 10;
            sum += (int) Math.pow(digit, digits);
            number /= 10;
        }

        if (sum == original) {
            System.out.println("Armstrong number");
        } else {
            System.out.println("Not an Armstrong number");
        }
    }
}

Output:

Armstrong number

This example is intended for positive integer input. For a robust solution, explicitly handle zero and reject negative values. For exact integer arithmetic, consider implementing an integer power calculation instead of relying on floating-point Math.pow().

22. Practice Problem 16: Find the Greatest Common Divisor (GCD)

Problem: Find the greatest common divisor of two positive integers using the Euclidean algorithm.

public class GCDDemo {
    public static void main(String[] args) {
        int a = 48;
        int b = 18;

        while (b != 0) {
            int remainder = a % b;
            a = b;
            b = remainder;
        }

        System.out.println("GCD: " + a);
    }
}

Output:

GCD: 6

Explanation: The algorithm repeatedly replaces the first number with the second and the second with their remainder. When the remainder becomes zero, the first number is the GCD.

23. Practice Problem 17: Check Whether a Number Is Perfect

Problem: A perfect number is a positive integer equal to the sum of its positive divisors excluding itself. For example, 6 is perfect because 1 + 2 + 3 = 6.

public class PerfectNumber {
    public static void main(String[] args) {
        int number = 28;
        int sum = 0;

        for (int i = 1; i <= number / 2; i++) {
            if (number % i == 0) {
                sum += i;
            }
        }

        if (number > 0 && sum == number) {
            System.out.println("Perfect number");
        } else {
            System.out.println("Not a perfect number");
        }
    }
}

Output:

Perfect number

Concepts used: for loop, modulus operator, if statement, and accumulation.

24. Practice Problem 18: Display All Even Numbers in a Range

Problem: Print all even numbers between 1 and 20.

public class EvenNumbers {
    public static void main(String[] args) {
        for (int i = 1; i <= 20; i++) {
            if (i % 2 == 0) {
                System.out.print(i + " ");
            }
        }
    }
}

Output:

2 4 6 8 10 12 14 16 18 20

Alternative approach: Start the loop at 2 and increase the counter by 2 each time. This avoids checking odd values.

for (int i = 2; i <= 20; i += 2) {
    System.out.print(i + " ");
}

25. Practice Problem 19: Create a Simple Calculator

Problem: Create a calculator that performs addition, subtraction, multiplication, or division based on a selected operator.

public class SimpleCalculator {
    public static void main(String[] args) {
        double a = 20;
        double b = 5;
        char operator = '/';

        switch (operator) {
            case '+':
                System.out.println(a + b);
                break;
            case '-':
                System.out.println(a - b);
                break;
            case '*':
                System.out.println(a * b);
                break;
            case '/':
                if (b != 0) {
                    System.out.println(a / b);
                } else {
                    System.out.println("Cannot divide by zero");
                }
                break;
            default:
                System.out.println("Invalid operator");
        }
    }
}

Output:

4.0

Explanation: The switch statement selects the calculation. The division case checks for zero before performing the operation. This example uses fixed values; a complete calculator can accept values and the operator from the user.

26. Common Errors and Troubleshooting

Error 1: Using = Instead of ==

Incorrect:

if (number = 10) {
    System.out.println("Ten");
}

Correct:

if (number == 10) {
    System.out.println("Ten");
}

The assignment operator = assigns a value, while == compares values.

Error 2: Forgetting to Update the Loop Counter

If a while loop never changes the variable used in its condition, the condition may remain true indefinitely.

Incorrect:

int i = 1;

while (i <= 5) {
    System.out.println(i);
}

Correct:

int i = 1;

while (i <= 5) {
    System.out.println(i);
    i++;
}

Error 3: Incorrect Loop Boundary

Using i < n instead of i <= n changes whether the final value is included. Choose the condition based on the exact range required.

Error 4: Integer Division

Problem: The expression 5 / 2 returns 2 when both operands are integers.

Solution: Use 5.0 / 2 or convert an operand to a floating-point type when a decimal answer is required.

Error 5: Incorrect Logical Conditions

Combining conditions with the wrong operator can produce unexpected results. For example, a number cannot be both less than 0 and greater than 10 at the same time.

// To check whether a number is outside the range 1 to 10:
if (number < 1 || number > 10) {
    System.out.println("Outside range");
}

Error 6: Forgetting break in a Traditional switch

Without a break statement, execution may continue into the following case. Add break statements when each case should finish independently.

Error 7: Overflow in Calculations

Integer types have a fixed range. Factorials, powers, and reversed numbers can exceed that range. Use a suitable type, validate input limits, or consider BigInteger for very large integer calculations.

27. Best Practices for Solving Java Problems

  • Understand the problem and expected output before writing code.
  • Use meaningful variable names such as sum, factorial, and isPrime.
  • Use parentheses to make complicated boolean expressions easier to understand.
  • Choose the loop type that best matches the problem.
  • Check loop initialization, termination conditions, and counter updates.
  • Test boundary values such as zero, one, negative numbers, and repeated values.
  • Keep calculations within the range of the selected data type.
  • Use break when further iterations are unnecessary, such as when a divisor is found.
  • Avoid unnecessarily complicated nested conditions.
  • Compile and run each program, then compare its output with the expected result.
  • For input-based programs, validate input before performing operations that require specific ranges.
  • Prefer readable logic over clever but difficult-to-maintain expressions.

28. Mini Project: Number Analysis Tool

Objective: Create a simple Java program that analyzes a positive integer and reports whether it is even or odd, counts its digits, calculates the sum of its digits, and checks whether it is prime.

import java.util.Scanner;

public class NumberAnalysisTool {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a non-negative integer: ");
        int number = scanner.nextInt();

        if (number < 0) {
            System.out.println("Please enter a non-negative integer.");
            scanner.close();
            return;
        }

        if (number % 2 == 0) {
            System.out.println("Type: Even");
        } else {
            System.out.println("Type: Odd");
        }

        int temp = number;
        int digitCount = 0;
        int digitSum = 0;

        do {
            int digit = temp % 10;
            digitSum += digit;
            digitCount++;
            temp /= 10;
        } while (temp != 0);

        System.out.println("Digit count: " + digitCount);
        System.out.println("Digit sum: " + digitSum);

        boolean isPrime = number > 1;

        for (int i = 2; i <= number / i; i++) {
            if (number % i == 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime) {
            System.out.println("Prime: Yes");
        } else {
            System.out.println("Prime: No");
        }

        scanner.close();
    }
}

Sample input:

Enter a non-negative integer: 123

Sample output:

Type: Odd
Digit count: 3
Digit sum: 6
Prime: Yes

Project concepts:

  • Scanner for user input.
  • if-else for making decisions.
  • while and do-while loops for processing digits.
  • Arithmetic and relational operators for calculations and comparisons.
  • Boolean variables for tracking whether a number is prime.
  • Input validation for negative values.

29. Additional Practice Questions

  1. Write a program to check whether a number is divisible by both 3 and 5.
  2. Find the smallest of three numbers using conditional statements.
  3. Print all odd numbers from 1 to 100.
  4. Calculate the sum of all even numbers between 1 and n.
  5. Print numbers from n down to 1 using a while loop.
  6. Count how many even and odd digits are present in a number.
  7. Find the product of all digits of a positive integer.
  8. Check whether a number is a strong number, where the sum of the factorials of its digits equals the original number.
  9. Print a triangle of numbers using nested loops.
  10. Find all prime numbers between 1 and 100.
  11. Calculate the power of a number using a loop without using Math.pow().
  12. Display the sum of the series 1 + 2 + 3 + ... + n.
  13. Print a number pattern in which each row contains repeated row numbers.
  14. Create a menu-driven calculator that repeats until the user chooses to exit.
  15. Write a program to determine whether a number is a perfect square.

30. Interview Questions and Answers

Q1. What is an operator in Java?

An operator is a symbol that performs an operation on one or more operands. Examples include +, -, *, ==, and &&.

Q2. What is the difference between == and =?

= assigns a value to a variable. == compares primitive values or checks reference identity for objects.

Q3. What is the difference between && and ||?

&& returns true only when both boolean conditions are true. || returns true when at least one condition is true. Both use short-circuit evaluation.

Q4. What is the difference between while and do-while?

A while loop checks its condition before executing the body. A do-while loop checks the condition after the body, so the body executes at least once.

Q5. What is the purpose of break?

The break statement terminates the nearest enclosing loop or traditional switch statement.

Q6. What is the purpose of continue?

The continue statement skips the remaining statements in the current loop iteration and moves to the next iteration.

Q7. How can you check whether a number is prime?

First check whether the number is greater than 1. Then test divisors starting at 2 up to its square root. If any divisor divides it evenly, it is not prime.

Q8. Why is the modulus operator useful?

The modulus operator returns a remainder. It is useful for checking divisibility, identifying even and odd numbers, and extracting digits.

Q9. What is a nested loop?

A nested loop is a loop inside another loop. It is often used for pattern printing, tables, and processing two-dimensional data.

Q10. What causes an infinite loop?

An infinite loop occurs when the termination condition never becomes false or when the loop is intentionally written to continue indefinitely.

Q11. What is operator precedence?

Operator precedence determines which operators are evaluated first in an expression. Parentheses can be used to specify the intended order clearly.

Q12. Why should edge cases be tested?

Edge cases reveal errors involving boundaries, zero, negative values, repeated values, invalid input, and numeric overflow.

31. Quick Revision Checklist

  • Arithmetic operators perform mathematical operations.
  • Relational operators compare values and return boolean results.
  • Logical operators combine or reverse boolean expressions.
  • Assignment operators update variable values.
  • The ternary operator is a compact alternative to a simple if-else expression.
  • if, if-else, else-if, and switch statements support decision-making.
  • for, while, and do-while loops repeat instructions.
  • break terminates the nearest loop or traditional switch statement.
  • continue skips the remainder of the current loop iteration.
  • Nested loops are useful for pattern printing and repeated comparisons.
  • Modulus helps with divisibility tests and digit-based problems.
  • Prime, palindrome, factorial, and Fibonacci problems are useful practice exercises.
  • Always check loop termination and numeric limits.

32. Conclusion

Practicing Java operators, conditions, and loops develops the logical foundation required for more advanced programming topics. Operators help perform calculations and comparisons, conditions determine which instructions execute, and loops make it possible to process sequences and solve repetitive problems efficiently.

By working through number-based exercises, pattern printing, and the Number Analysis Tool mini project, learners can build confidence in writing, testing, and debugging Java programs. Consistent practice with different inputs and edge cases is the key to improving problem-solving ability and preparing for Core Java coding interviews.

33. Additional Learning Resources

Previous Next
whatsapp